package com.zeng.context;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @author zyb
 * @date 2021-03-07 10:12
 */
public class ComponentContextInitializerListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        ComponentContext componentContext = new ComponentContext();
        componentContext.init(servletContext);
        registerShutdownHook(componentContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }

    public void registerShutdownHook(ComponentContext componentContext) {
        Thread shutdownHook = new Thread(() -> componentContext.destroy());
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }
}
